﻿using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;

namespace Syufy.BINLookup.Web.Controllers.Api
{
    /// <summary>
    /// Web API for Location Services.
    /// </summary>
    [ApiExplorerSettings(IgnoreApi = true)]
    public class LocationController : ApiController
    {
        /// <summary>
        /// Get location detail from GeoPlugin.net
        /// </summary>
        /// <returns>GeoPlugin object.</returns>
        public async Task<IHttpActionResult> Get(string latitude, string longitude)
        {
            string result = string.Empty;
            
            // Acceptable Use Policy: http://www.geoplugin.com/aup
            using (var client = new HttpClient { BaseAddress = new Uri("http://www.geoplugin.net") })
            {
                var response = await client.GetAsync("/extras/location.gp?format=json&lat=" + latitude + "&long=" + longitude).ConfigureAwait(false);

                //response.EnsureSuccessStatusCode();

                await response.Content.ReadAsStringAsync().ContinueWith((Task<string> content) =>
                {
                    if (content.IsFaulted)
                    {
                        throw content.Exception;
                    }

                    result = content.Result;
                });
            }

            return Ok(result);
        }
    }
}
